/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import javax.annotation.PostConstruct;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.RegisterService;
import com.lmx.persistence.service.UserService;
import com.lmx.repoDomain.exception.BusinessException;
import io.katharsis.repository.annotations.JsonApiSave;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.repoDomain.tmodel.business.Organization;
import com.lmx.repoDomain.tmodel.business.User;

import io.katharsis.repository.annotations.JsonApiResourceRepository;

@JsonApiResourceRepository(User.class)
@Component
public class UserRepository extends BaseRepository<User> {
	@Autowired
	private RegisterService registerService;

	@Autowired
	private UserService userService; 

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(User.class);
	}

	@Override
	@JsonApiSave
	public User save(User user) {
		// final BaseDataEntity bd = (BaseDataEntity)entity;
		String action = ActionContextHolder.getContext().getAction();
		if (user.getId() == null) {
			// 创建user时查重
			if (userService.getUsersByLoginName(user) != null) {
				user.setErrcode(4);// 用户名重复
				throw new BusinessException(null, CommonConstants.ERROR_CODE.NAME_ERROR.label(), null);
//				return user;
			}
//			if (userService.getUsersByCardCode(user) != null) {
//				user.setErrcode(3);// 身份证重复
//				return user;
//			}
			Organization org=new Organization();
			org.setId(ActionContextHolder.getContext().getUser().getOrg().getId());
			user.setOrg(org);//机构
			dslJpaService.create(user);
		} else {
			// 机构编辑时修改管理员登录手机帐号
			User userOld=userService.getUserById(user.getId());
			if (StringUtils.isNotBlank(action) && "checkAuthCode".equals(action)) {
				String authCode = ActionContextHolder.getAuthCodeHolder().get(userOld.getLoginName());
				if (StringUtils.isBlank(authCode) || !authCode.equals(user.getAuthCode())) {
					user.setErrcode(ICommonConstants.REGFAILCAUSE.AUTHCODEFAIL.ordinal());// 验证码验证失败
					return user;
				}
				if (!StringUtils.isBlank(authCode) && authCode.equals(user.getAuthCode())) {
					user.setErrcode(1);// 验证码验证成功
					return user;
				}
			}
			if (StringUtils.isNotBlank(action) && "editLoginName".equals(action)) {
				String authCode = ActionContextHolder.getAuthCodeHolder().get(user.getLoginName());
				if (StringUtils.isBlank(authCode) || !authCode.equals(user.getAuthCode())) {
					user.setErrcode(ICommonConstants.REGFAILCAUSE.AUTHCODEFAIL.ordinal());// 验证码验证失败
					return user;
				} else {
					String newPd = CommonUtil.stringMD5(user.getLoginName());
					user.setPasscode(newPd);
					dslJpaService.update(user);
				}
			} else {
				// 修改user时查重
				User userTemp = userService.getUsersByLoginName(user);
				if (userTemp != null) {
					if (!userTemp.getId().equals(user.getId())) {
						user.setErrcode(4);// 用户名重复
						throw new BusinessException(null, CommonConstants.ERROR_CODE.NAME_ERROR.label(), null);
					}
				}
				//  如果名字或者头像为空   将employee名字以及头像复制到user中
				if(user.getName()==null||"".equals(user.getName())){
					if (user.getEmployee() != null) {
						if (user.getEmployee().getName() != null) {
							user.setName(user.getEmployee().getName());
						}
					}
				}
				if(user.getAvatar()==null||"".equals(user.getAvatar())){
					if (user.getEmployee() != null) {
						if (user.getEmployee().getAvatar() != null) {
							user.setAvatar(user.getEmployee().getAvatar());
						}
					}
				}
				dslJpaService.update(user);
			}
		}
		return user;
	}

}
